import mqtt from 'mqtt';
import url from 'url';

const state = {
  client: null,
  times: 1,
  topic: '/World',
  mqttHost: '123.123.123.123',
  mqttPort: 8083,
  mqttUser: '',
  mqttPassword: '',
  clientId: 'sssssssa'
}

const actions = {
  initClient ({state}) {
    state.client = mqtt.connect(url.parse(`ws://${state.mqttHost}:${state.mqttPort}`), {
      clientId: state.clientId,
      // username: state.mqttUser,
      // password: state.mqttPassword,
      path: '/mqtt'
    })
  },
  initConnect ({state}) {
    state.client.on('connect', () => {
      console.log('mqtt 连接成功')
    })
  },
  initSubscribe () {
    state.client.subscribe(state.topic, () => {
      console.log(`${state.topic} 订阅成功`)
    })
  },

  taskMqtt ({state, dispatch}, hand) {

    if (!state.client) {
      dispatch('initClient')
      dispatch('initSubscribe').then(() => {
        state.client.on('message', (topic, message, data) => {
          console.log(message.toString())
          if (hand) {
            hand(message.toString())
          }
        })
      })
    }
    if (!state.client.connected) {
      dispatch('initConnect')
    }
  },

  sendMessage ({state, dispatch}, message) {
    let sendMsg = `${message}\r\n`;
    if (this.client) {
      this.client.publish(state.topic, sendMsg);
    } else {
      console.log('连接失败')
    }
  },

  closeSub () {
    console.log('退出登录，断开连接', state.topic)
    if (state.client) {
      state.client.unsubscribe(state.topic)
      if (state.client.connected) {
        state.client.end()
      }
      setTimeout(() => {
        state.client = null
      })
    }
  }
}

const mutations = {}

const getters = {}

export default {
  state,
  actions,
  mutations,
  getters
}